//
//  StudentAddViewController.m
//  Eath
//
//  Created by mao on 10/29/14.
//  Copyright (c) 2014 yuhaya. All rights reserved.
//

#import "StudentAddViewController.h"
#import "Tool.h"
#import "User.h"
#import "Database.h"
#import "SchoolListTableViewController.h"
#import "DateAlertController.h"

@interface StudentAddViewController ()

@end

@implementation StudentAddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
   
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, [Tool tableHeight] - 30) style:UITableViewStyleGrouped];
    self.table.dataSource = self;
    self.table.delegate = self;
    [self.view addSubview:self.table];
    
    self.view.backgroundColor =[UIColor colorWithRed:0.94 green:0.94 blue:0.96 alpha:1];
    
    self.title = @"添加学生";
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame =CGRectMake(0, 0, 40, 30);
    
    if(self.stu != nil){
        
        [rightBtn setTitle:@"更新" forState:UIControlStateNormal];
        [rightBtn addTarget:self action:@selector(updateStudent) forControlEvents:UIControlEventTouchUpInside];
    }else{
        [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
        [rightBtn addTarget:self action:@selector(addStudent) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.photo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"default_head"]];
    
    CGRect textFrame = CGRectMake(100, 0, 200, 50);
    UIFont * font = [UIFont systemFontOfSize:13];
    
    self.name = [[UITextField alloc] initWithFrame:textFrame];
    self.name.delegate = self;
    self.name.placeholder = @"输入姓名";
    self.name.textAlignment = NSTextAlignmentRight;
    self.name.font = font;
    
    self.sex = [[DCRoundSwitch alloc] initWithFrame:CGRectMake(220, 10, 80, 30)];
    [self.sex setOnText:@"男"];
    [self.sex setOffText: @"女"];
    
    self.school = [[UITextField alloc] initWithFrame:textFrame];
    [self.school setEnabled:NO];
    self.school.delegate = self;
    self.school.placeholder = @"选择学校";
    self.school.textAlignment = NSTextAlignmentRight;
    self.school.font = font;
    
    self.card = [[UITextField alloc] initWithFrame:textFrame];
    self.card.delegate = self;
    self.card.placeholder = @"输入卡号";
    self.card.textAlignment = NSTextAlignmentRight;
    self.card.font = font;
    
    self.grade = [[UITextField alloc] initWithFrame:textFrame];
    self.grade.delegate = self;
    self.grade.placeholder = @"输入年级信息";
    self.grade.textAlignment = NSTextAlignmentRight;
    self.grade.font = font;
    
    self.class_name = [[UITextField alloc] initWithFrame:textFrame];
    self.class_name.delegate = self;
    self.class_name.placeholder = @"输入班级信息";
    self.class_name.textAlignment = NSTextAlignmentRight;
    self.class_name.font = font;
    
    self.relation = [[UITextField alloc] initWithFrame:textFrame];
    self.relation.delegate = self;
    self.relation.placeholder = @"输入亲属关系";
    self.relation.textAlignment = NSTextAlignmentRight;
    self.relation.font = font;
    
    self.enrol_time = [[UITextField alloc] initWithFrame:textFrame];
    [self.enrol_time setEnabled:NO];
    self.enrol_time.delegate = self;
    self.enrol_time.placeholder = @"输入入学时间";
    self.enrol_time.textAlignment = NSTextAlignmentRight;
    self.enrol_time.font = font;
    
    if (self.stu != nil) {
        DLog(@"%@",self.stu);
        self.photo.image = [UIImage imageNamed:self.stu.photo];
        self.name.text = self.stu.name;
        self.sex.on = self.stu.sex ? YES : NO;
        self.school.text = self.stu.school_name;
        self.school_id = self.stu.school_id;
        self.card.text = self.stu.card;
        self.class_name.text = self.stu.class_name;
        self.grade.text = self.stu.grade;
        self.relation.text = self.stu.relation;
        self.enrol_time.text = self.stu.enrol_time;
        self.identify = self.stu.identify;
    }
}


-(void) viewWillAppear:(BOOL)animated {
    //注册键盘出现通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardHide:)
                                                 name: UIKeyboardDidHideNotification object:nil];
    [super viewWillAppear:animated];
}


-(void) viewWillDisappear:(BOOL)animated {
    //解除键盘出现通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidShowNotification object:nil];
    //解除键盘隐藏通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidHideNotification object:nil];
    
    [super viewWillDisappear:animated];
}

//自定义键盘打开时触发的事件
-(void) keyboardShow: (NSNotification *)notif {
    
    NSDictionary * info = [notif userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    [UIView animateWithDuration:0.3f animations:^{
//        CGRect curFrame=self.view.frame;
//        curFrame.origin.y = self.table.frame.origin.y - self.height;
//        self.view.frame=curFrame;
        
        CGRect tableFrame = self.table.frame;
        tableFrame.size.height = [Tool tableHeight] - kbSize.height;
        self.table.frame = tableFrame;
    }];
}

//自定义键盘关闭时触发的事件
-(void) keyboardHide: (NSNotification *)notif {
    [UIView animateWithDuration:0.3f animations:^{
//        CGRect curFrame=self.view.frame;
//        CGRect status = [[UIApplication sharedApplication] statusBarFrame];
//        curFrame.origin.y = self.navigationController.navigationBar.frame.size.height + status.size.height;
//        self.view.frame=curFrame;
        
        
        CGRect tableFrame = self.table.frame;
        tableFrame.size.height = [Tool tableHeight] - 30;
        self.table.frame = tableFrame;
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) updateStudent
{
    NSDictionary * login_user = [User loginInfo];
    NSMutableDictionary * stu = [NSMutableDictionary dictionary];
    stu[@"user_id"] = login_user[@"id"];
    stu[@"name"] = self.name.text;
    stu[@"gender"] = self.sex.on ? @"0" : @"1";
    stu[@"school_id"] = self.school_id;
//    stu[@"school_name"] = self.school.text;
    stu[@"grade"] = self.grade.text;
    stu[@"class_name"] = self.class_name.text;
    stu[@"card"] = self.card.text;
    stu[@"enrol_time"] = self.enrol_time.text;
    stu[@"relation"] = self.relation.text;
    stu[@"id"] = self.identify;
    
    NSString * token = [User token];
    DLog(@"%@",stu);
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString * url_stus_get = [NSString stringWithFormat:@"%@?token=%@",URL_STU_UPDATE,token];
    
    [manager POST:url_stus_get parameters:stu success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * redata = responseObject;
//        NSArray * data = redata[@"data"];
        NSString * code = redata[@"code"];
        
        if(code.intValue  == 0){
//            DLog(@"%@",data);
            [Tool showMessage:@"更新成功!"];
            [[Database sharedDatabase] syncStudents:login_user[@"id"]];
            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            [Tool showMessage:redata[@"msg"]];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Tool showMessage:[error localizedDescription]];
    }];
}

- (void) addStudent
{
    NSDictionary * login_user = [User loginInfo];
    NSMutableDictionary * stu = [NSMutableDictionary dictionary];
    stu[@"user_id"] = login_user[@"id"];
    stu[@"name"] = self.name.text;
    stu[@"gender"] = self.sex.on ? @"0" : @"1";
    stu[@"school_id"] = self.school_id;
//    stu[@"school_name"] = self.school.text;
    stu[@"grade"] = self.grade.text;
    stu[@"class_name"] = self.class_name.text;
    stu[@"card"] = self.card.text;
    stu[@"enrol_time"] = self.enrol_time.text;
    stu[@"relation"] = self.relation.text;
    
    NSString * token = [User token];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString * url_stus_get = [NSString stringWithFormat:@"%@?token=%@",URL_STU_ADD,token];
    
    [manager POST:url_stus_get parameters:stu success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary * redata = responseObject;
//        NSArray * data = redata[@"data"];
        NSString * code = redata[@"code"];
        DLog(@"===%@",redata);
        if(code.intValue  == 0){
            [Tool showMessage:@"添加成功!"];
            [[Database sharedDatabase] syncStudents:login_user[@"id"]];
            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            [Tool showMessage:redata[@"msg"]];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Tool showMessage:[error localizedDescription]];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0){
        return 4;
    }else{
        return 5;
    }
}

// Default is 1 if not implemented
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0 && indexPath.row == 0){
        
        return 90;
        
    }else{
        
        return 50;
    }
}



// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [[UITableViewCell alloc] init];
    CGRect frame = CGRectMake(20, 0, 80, 50);
    UILabel * item = [[UILabel alloc] initWithFrame:frame];
    item.font = [UIFont systemFontOfSize:13];
    
    if(indexPath.section == 0){
        
        if(indexPath.row == 0){
            
            item.text = @"头像";
            item.frame = CGRectMake(20, 0, 80, 90);
            self.photo.frame = CGRectMake(240, 12, 66, 66);
            self.photo.tag = indexPath.section + indexPath.row;
            [cell.contentView addSubview:self.photo];
            
        }else{
            
            if (indexPath.row == 1){
                item.text = @"姓名";
                self.name.tag = indexPath.section*10 + indexPath.row;
                [cell.contentView addSubview:self.name];
                
            }else if (indexPath.row == 2){
                item.text = @"性别";
                self.sex.tag = indexPath.section*10 + indexPath.row;
                [cell.contentView addSubview:self.sex];
                
            }else if (indexPath.row == 3){
                item.text = @"卡号";
                self.card.tag = indexPath.section*10 + indexPath.row;
                [cell.contentView addSubview:self.card];
            }
            
        }
        
    }else{
        
        if (indexPath.row == 0){
            item.text = @"所属学校";
            self.school.tag = indexPath.section*10 + indexPath.row;
            [cell.contentView addSubview:self.school];

            
        }else if (indexPath.row == 1){
            
            item.text = @"所属年级";
            self.grade.tag = indexPath.section*10 + indexPath.row;
            [cell.contentView addSubview:self.grade];
        }else if (indexPath.row == 2){
            
            item.text = @"所属班级";
            self.class_name.tag = indexPath.section*10 + indexPath.row;
            [cell.contentView addSubview:self.class_name];
        }else if (indexPath.row == 3){
            
            item.text = @"亲属关系";
            self.relation.tag = indexPath.section*10 + indexPath.row;
            [cell.contentView addSubview:self.relation];
        }else if(indexPath.row == 4){
            
            item.text = @"入学时间";
            self.enrol_time.tag = indexPath.section*10 + indexPath.row;
            [cell.contentView addSubview:self.enrol_time];
        }
    }
    
    [cell.contentView addSubview:item];
    return cell;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
//    [Tool showMessage:@"end edit"];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
//    if(textField.tag == 1 || textField.tag ==2 || textField.tag ==3){
//        
//        self.height = textField.tag * 50;
//    }else{
//        self.height = (textField.tag - 10) * 50 + 250;
//    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if(indexPath.section == 1 && indexPath.row == 0){
        //加载学校列表信息
        SchoolListTableViewController * school_list = [[SchoolListTableViewController alloc] init];
        school_list.student_add = self;
        [self.navigationController pushViewController:school_list animated:YES];
        
    }else if (indexPath.section == 1 && indexPath.row == 4){
        
        DateAlertController * ca = [DateAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        UITextField * label = (UITextField *)[cell viewWithTag:(indexPath.section*10 + indexPath.row)];
        ca.label = label;
        [self presentViewController:ca animated:YES completion:nil];
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
